package com.mymall.serve.config;

import com.google.common.collect.Maps;
import com.mymall.serve.filter.ActuatorFilter;
import com.mymall.serve.interceptor.RestApiInteceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Map;

/**
 * Web 配置类
 *
 * @author weiwei
 * @since 2020-04-29 20:58
 **/
@Configuration
@ConditionalOnBean(RestApiInteceptor.class)
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private RestApiInteceptor userInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userInterceptor)
                .addPathPatterns("/**");
    }

    /**
     * 白名单配置
     * @return
     */
    @Bean("actuatorFilter")
    @Order(1)
    public FilterRegistrationBean requestFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        ActuatorFilter requestFilter = new ActuatorFilter();
        registration.setFilter(requestFilter);
        registration.addUrlPatterns("/actuator","/actuator/*");
        Map<String, Object> params = Maps.newHashMap();
        params.put("whiteIps", "127.0.0.1");
        registration.setInitParameters(params);
        return registration;
    }


    /*
    // springboot2.4 跨域配置使用
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET","HEAD","POST","DELETE","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }*/
}
